import { ConfigProvider, message } from 'antd'
import './App.scss'
import CodeContainer, { ICodeContainerRef } from './components/CodeContainer'
import { CodeContainerType } from './core/types'
import { useRef, useState } from 'react'
import axios from 'axios'
import { languageMap } from './common/constants'
import { RetweetOutlined } from '@ant-design/icons'

function App() {
  const cRef = useRef<ICodeContainerRef>(null)
  const rustRef = useRef<ICodeContainerRef>(null)
  const [translateLoading, setTranslateLoading] = useState<boolean>(false)

  const handleTranslate = () => {
    if (!cRef.current?.dirData) {
      message.warning('Please import C code')
    }
    if (cRef.current && rustRef.current && cRef.current.dirData && !translateLoading) {
      setTranslateLoading(true)
      rustRef.current.setLoading(true)
      rustRef.current.setDirData(void 0)
      message.loading('Translating in progress, please wait a moment')
      const cData = cRef.current.dirData
      axios.post<{ status: number, output: { path: string, code: string }[] }>('https://api.c2rust.cn/api/transcode/from_json_to', cData).then((res) => {
        if (res.data.status !== 0) {
          message.error('Translating failed')
          setTranslateLoading(false)
          rustRef.current?.setLoading(false)
        }
        if (rustRef.current && res.data.status === 0) {
          const data = {
            projectName: cData.projectName + '-rust',
            content: res.data.output.map((item) => {
              const fileExtension = item.path.split('.').pop()?.toLowerCase();
              const detectedLanguage = fileExtension ? languageMap[fileExtension] : 'plaintext';
              return ({
                ...item,
                codeType: detectedLanguage
              })
            })
          }
          rustRef.current.setDirData(data)
          rustRef.current.createProjectToServer(data)
          setTranslateLoading(false)
          rustRef.current.setLoading(false)
          message.success('Transfer successful')
        }
      })
    }
  }

  return (
    <>
      <ConfigProvider
        theme={{
          token: {
            colorPrimary: '#41521f',
          },
        }}
      >
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'space-between', height: '100vh' }}>
          <CodeContainer ref={cRef} type={CodeContainerType.FROM} />
          <div className='btn-wrap'>
            <button className='btn translate-btn' onClick={handleTranslate}><RetweetOutlined />{translateLoading ? 'Translating' : 'Translate'}</button>
            {/* <button className='btn translate-btn'>Compare</button> */}
          </div>
          <CodeContainer ref={rustRef} type={CodeContainerType.TO} />
        </div>
      </ConfigProvider>
    </>
  )
}

export default App
